/*
 * const_magic.hpp
 *
 *  Created on: 2023年11月11日
 *      Author: Dylan.Gao
 */

#ifndef _DM_CONST_MAGIC_HPP_
#define _DM_CONST_MAGIC_HPP_

#include <dm/magic.hpp>

namespace dm{

class CConstMagic{
public:
	typedef CMagic::magic_t magic_t;

	CConstMagic( const volatile magic_t* shared ):m_shared(shared){
		update();
	}

	CConstMagic( const CConstMagic& magic ):m_local(magic.m_local),m_shared(magic.m_shared){
	}

	CConstMagic( const CMagic& magic ):CConstMagic(magic.m_shared){
	}

	CConstMagic& operator=( const CConstMagic& magic ){
		m_shared = magic.m_shared;
		update();

		return *this;
	}

	CConstMagic& operator=( const CMagic& magic ){
		m_shared = magic.m_shared;
		update();

		return *this;
	}

	inline bool ifValid()const{
		if( CMagic::MaskZero!=(m_local&CMagic::MaskZero) )	// 0区不为0
			return false;

		if( (m_local&CMagic::MaskData) != (m_local>>16&CMagic::MaskData) )	// 数据区不一致
			return false;

		return true;
	}

	inline void update(){
		if( m_shared )
			m_local = *m_shared;
		else
			m_local = 0;
	}

	inline bool ifUpdated()const{
		return m_shared && m_local==(*m_shared);
	}

	inline const magic_t& local()const{
		return m_local;
	}

	inline magic_t shared()const{
		return m_shared?*m_shared:0;
	}

private:
	magic_t m_local;
	const volatile magic_t* m_shared;
};

}

#endif /* _DM_CONST_MAGIC_HPP_ */
